package com.cdream.bank1.seata.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdream.bank.Bank2Client;
import com.cdream.bank.domain.AccountInfo;
import com.cdream.bank1.seata.mapper.AccountInfoMapper;
import com.cdream.bank1.seata.service.AccountInfoService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zs
 * @since 2021-08-29
 */
@Slf4j
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements AccountInfoService {
    @Autowired
    AccountInfoMapper accountInfoMapper;
    @Autowired
    Bank2Client bank2Client;
    //张三转账
    @GlobalTransactional
    @Override
    @Transactional
    public void updateAccountBalance(String accountNo, Double amount) {
        log.info("******** Bank1 Service Begin ... xid: {}" , RootContext.getXID());
        //张三扣减金额
        accountInfoMapper.updateAccountBalance(accountNo,-1 * amount);
        //向李四转账
        String remoteRst = bank2Client.transfer(amount);
        //远程调用失败
        if(remoteRst.equals("fallback")){
            throw new RuntimeException("bank1 下游服务异常");
        }
        //人为制造错误
        if(amount==3){
            throw new RuntimeException("bank1 make exception 3");
        }
    }
}
